package com.lagou.service.impl;

import com.lagou.dao.mapper.AuthCodeMapper;
import com.lagou.dao.pojo.AuthCode;
import com.lagou.service.CodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class CodeServiceImpl implements CodeService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AuthCodeMapper authCodeMapper;

    @Override
    public String createCode(String email) {
        int count = ThreadLocalRandom.current().nextInt(1000000);
        String code = String.format("%06d", count);
        //写入数据库
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        long curr = System.currentTimeMillis();
        long end = curr + 10*60000;
        authCode.setCreatetime(new Date(curr));
        authCode.setExpiretime(new Date(end));

        authCodeMapper.insertAuthCode(authCode);

        return code;
    }

    @Override
    public int checkCode(String email, String code) {
        try {
            List<AuthCode> auths = authCodeMapper.findUserCode(email, code);
            if (auths==null || auths.size()==0) return 1;
            long curr = System.currentTimeMillis();
            for (AuthCode auth : auths) {
                long begin = auth.getCreatetime().getTime();
                long end = auth.getExpiretime().getTime();
                if (begin<curr && end>curr){
                    return 0;
                }
            }
            return 2;
        } catch (Exception e) {
            logger.error("", e);
            return 2;
        }
    }

}
